package gam.t1.appraisal2;

import gam.t1.appraisal2.dinv.DataInventory;
import gam.t1.appraisal2.reninv.RenderInventory;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.EventPriority;
import org.bukkit.event.Listener;
import org.bukkit.event.inventory.InventoryClickEvent;
import org.bukkit.event.inventory.InventoryCloseEvent;
import org.bukkit.inventory.Inventory;
import org.bukkit.inventory.ItemStack;

import java.util.Map;

public final class InvClickEvent implements Listener {
    @EventHandler(priority = EventPriority.LOWEST)
    public void $out(InventoryCloseEvent e){
        Player p = (Player) e.getPlayer();
        if (isClickInventory(p)){
            Data.removeInventory(p.getUniqueId());
            Data.removeAppraisalDataInventory(p.getUniqueId());
        }
    }
    @EventHandler(priority = EventPriority.LOWEST)
    public void $inv(InventoryClickEvent e){
        if (e.isCancelled()) return;
        Player p = (Player) e.getWhoClicked();
        if (isClickInventory(p)){
            int c = e.getSlot();
            DataInventory v1 = Data.getAppraisalDataInventory(p.getUniqueId());
            if (v1 != null){
                e.setCancelled(true);
                Map<Integer, ItemStack> v2 = v1.runClickBlock(c);
                RenderInventory.render(v2,p);
            }
        }
    }
    private boolean isClickInventory(Player player){
        Inventory v1 = player.getOpenInventory().getTopInventory();
        Inventory v2 = Data.getInventory(player.getUniqueId());
        return v1.equals(v2);
    }
}
